package com.coocaa.ops.admin.v1.timedtask.convert;

import com.coocaa.ops.admin.v1.timedtask.model.JobInfoModel;
import com.coocaa.ops.admin.v1.timedtask.model.QuartzSchedulerModel;
import com.coocaa.ops.common.tool.base.InstanceUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobKey;
import org.quartz.Scheduler;

import java.util.List;

/**
 * @author bijiahao
 * @date : 2019/8/6.
 * @description 定时相关的查询 转化器
 *
 */
public final class TimedTaskQueryConverter {


    public static QuartzSchedulerModel getQuartzSchedulerModel(Scheduler scheduler) throws Exception {
        return new QuartzSchedulerModel(scheduler.getSchedulerName(), scheduler.getJobGroupNames(), scheduler.getTriggerGroupNames(), getJobList(scheduler.getCurrentlyExecutingJobs()));
    }

    private static List<JobInfoModel> getJobList(List<JobExecutionContext> contextList) {
        if (CollectionUtils.isEmpty(contextList)) {
            return InstanceUtil.newArrayList(0);
        }
        List<JobInfoModel> jobList = InstanceUtil.newArrayList(contextList.size());
        for (JobExecutionContext context : contextList) {
            JobInfoModel jobInfoModel = getJob(context);
            if (null != jobInfoModel) {
                jobList.add(jobInfoModel);
            }
        }
        return jobList;
    }

    private static JobInfoModel getJob(JobExecutionContext context) {
        if (null == context) {
            return null;
        }
        JobDetail jobDetail = context.getJobDetail();
        if (null == jobDetail) {
            return null;
        }
        JobKey jobKey = jobDetail.getKey();
        if (null == jobKey) {
            return null;
        }
        return new JobInfoModel(jobKey.getGroup(), jobKey.getName());
    }
}
